package com.lingchou.cloud.process.client.listener;

import com.lingchou.cloud.process.api.enums.ProcessNodeTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.HistoryService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.variable.api.history.HistoricVariableInstance;
import org.springframework.stereotype.Service;
import com.lingchou.cloud.process.client.controller.ProcessBaseApiImpl;

import java.io.Serializable;

/**
 * 判断完成的条件方法，用于流程构建时 {@link ProcessBaseApiImpl#deploy}
 */
@Slf4j
@Service("completeExecution")
public class CompleteExecution implements Serializable {
    private static final long serialVersionUID = -9007042856896394445L;
    private final transient HistoryService historyService;

    public CompleteExecution(HistoryService historyService) {
        this.historyService = historyService;
    }

    /**
     * 判断完成条件
     *
     * @param execution     当前执行器
     * @param typeParamName 类型参数key
     */
    public boolean completeTask(DelegateExecution execution, String typeParamName) {
        log.info("completeTask:" + typeParamName);
        //所有人员审批
        int nrOfInstances = (Integer) execution.getVariable("nrOfInstances"); //总的会签任务数量
        int nrOfCompletedInstances = (Integer) execution.getVariable("nrOfCompletedInstances"); //总的会签任务数量---已执行
        //根据执行器获取流程实例ID，与类型参数，作为参数查询变量值
        HistoricVariableInstance historicVariableInstance = historyService.createHistoricVariableInstanceQuery()
                .processInstanceId(execution.getProcessInstanceId())
                .variableName(typeParamName).singleResult();
        String typeValue = historicVariableInstance.getValue().toString();
        //判断变量值 做完成条件判断
        ProcessNodeTypeEnum typeEnum = ProcessNodeTypeEnum.valueOf(typeValue);
        boolean result = false;
        switch (typeEnum) {
            case SINGLE:
            case OR_SIGN:
                result = nrOfCompletedInstances == 1;
                break;
            case WITH_SIGN:
                result = nrOfCompletedInstances == nrOfInstances;
                break;
            default:
                log.error("completeExecution typeEnum error");
                break;
        }
        return result;
    }
}
